/*
** main.c for  in /home/gomes_m//my-project-a-moi/client
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Sun Jul 28 13:36:18 2013 mickael gomes
** Last update Wed Jul 31 01:03:15 2013 mickael gomes
*/

#include		<unistd.h>
#include		<stdio.h>
#include		<stdlib.h>
#include		<signal.h>
#include		<struct.h>
#include		<prototypes.h>

int			server_id;

char			**get_env_paths(char **env)
{
  int			i = 0;

  while (env[i])
    {
      if (!my_strncmp(env[i], PATH, my_strlen(PATH)))
	return (my_str_to_wordtab_plus(env[i]));
      i++;
    }
  my_putstr(2, "There's no path in the environement.\n", 0);
  return (NULL);
}

void			send_closing(int signal)
{
  (void)(&signal);
  xwrite(server_id, "closing", my_strlen("closing"));
}

void			get_signal()
{
  signal(SIGHUP, send_closing);
}

void			display_current_dir(t_socket *socket, t_cmd *cmd)
{
  if (cmd->local == 0)
    {
      printf("\033[22;31m\n");
      xwrite(server_id, "pwd\n", my_strlen("pwd\n"));
      cmd->cmd = "pwd";
      server_response(socket, cmd);
      printf("\033[0m\n");
    }
  else
    {
      printf("\033[22;32m\n");
      cmd->cmd = "pwd";
      get_fork(cmd, socket);
      printf("\033[0m\n");
    }
}

int			main(int ac, char **av, char **env)
{
  t_socket		socket;
  t_cmd			cmd;
  t_cmd			tmp;

  if (ac != 3)
    my_putstr(2, "Ip and port required.\nUSAGE : IP PORT\n", 1);
  init_socket(&socket, av[1], xatoi(check_port_validity(av[2])));
  server_id = socket.fd;
  init_cmd(&cmd, env);
  tmp.arguments = xmalloc(1024 * sizeof(char));
  tmp.arguments = my_strcat_plus(getcwd(tmp.arguments, 1024), "repo", '/');
  tmp.home = tmp.arguments;
  my_cd(&tmp, &socket);
  get_signal();
  while (12)
    {
      display_current_dir(&socket, &cmd);
      xwrite(1, "$>", 3);
      get_cmd(&cmd, &socket);
    }
}
